import React, { Component, useContext, useState, useEffect, useRef } from 'react';
import { Table, Input, Form, Select } from 'antd';
import { apiGetPlatformSetList, apiGetPlatformSetEdit } from '@/request/configuration'
import '../style/index.less'

const EditableContext = React.createContext(null);


const timeInfo = [
  { value: "1分钟" },
  { value: "2分钟" },
  { value: "3分钟" },
  { value: "4分钟" },
  { value: "5分钟" },
  { value: "6分钟" },
  { value: "7分钟" },
  { value: "8分钟" },
  { value: "9分钟" },
  { value: "10分钟" },
  { value: "20分钟" },
  { value: "30分钟" },
];

const timeMap2Value = {
  "1分钟": "1",
  "2分钟": "2",
  "3分钟": "3",
  "4分钟": "4",
  "5分钟": "5",
  "6分钟": "6",
  "7分钟": "7",
  "8分钟": "8",
  "9分钟": "9",
  "10分钟": "10",
  "20分钟": "20",
  "30分钟": "30",
};

const addressArr = [];

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};
let flag = true;

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const arr = ['售后政策', '正品保障', '打车协议']
  let defaultArr;
  if (editable && arr.includes(record.platformSetKey)) {
    for (let k in addressArr) {
      if (addressArr[k].value === record.platformSetShowValue) {
        defaultArr = addressArr[k].value;
        break;
      }
    }
  }
  var defaultTime;

  if (editable && record.platformSetUnit === '分钟') {
    for (let k in timeMap2Value) {
      if (timeMap2Value[k] === record.platformSetShowValue) {
        defaultTime = k;
        break;
      }
    }
  }

  const [editing, setEditing] = useState(false);
  const [timeSelected, setTimeSelected] = useState(defaultTime);
  const [addressArrs, setaddressArrSelected] = useState(addressArr);

  const [dArr, setdArr] = useState(defaultArr);
  let pageNo = 1;

  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  const rules1 = [
    { required: true, message: '此项未必填项' },
    { pattern: /^[1-9]\d*$/, message: '只能输入正整数' }
  ]
  const rules2 = [
    { required: true, message: '此项未必填项' },
    { pattern: /^\d+(\.\d{0,2})?$/, message: '只能输入正数且最多两位小数' }
  ]
  const rules3 = [
    { required: true, message: '此项未必填项' },
  ]

  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }

    if (flag) {
      React.$post('/admin/activityLink/page', {
        pageNo,
        pageSize: -1
      }).then(res => {
        if (res.code === 0) {
          res.data.map(item => {
            addressArr.push({
              value: item.activityLink,
              label: item.activityName,
            })
          })
        }
      })
    }
    flag = false
  }, []);
  // const getMenu = () => {
  //   console.log('pageNossssss', pageNo);
  //   React.$post('/admin/activityLink/page', {
  //     pageNo,
  //     pageSize: 10
  //   }).then(res => {
  //     if (res.code === 0) {
  //       res.data.map(item => {
  //         console.log('arrr', [...addressArrs, {
  //           value: item.activityLink,
  //           label: item.activityName,
  //         }]);
  //         setaddressArrSelected([...addressArr, {
  //           value: item.activityLink,
  //           label: item.activityName,
  //         }])
  //       })
  //     }
  //   })
  // };

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const setRules = (record) => {
    let rules = []
    switch (record.platformSetUnit) {
      case '天':
        rules = rules1
        break;
      case '%':
        rules = rules2
        break;
      case ' ':
        rules = rules3
        break;
      default:
        rules = rules3
    }
    return rules;
  }

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
    }
  };
  const selectChange = async (e) => {
    setTimeSelected(e);
    handleSave({ ...record, platformSetShowValue: `${timeMap2Value[e]}` });
  };

  const selectUrlChange = async (e) => {
    setdArr(e)
    handleSave({ ...record, platformSetShowValue: `${e}` });
  };

  let childNode = children;

  if (editable) {
    if (record.platformSetUnit === '分钟') {
      return <td {...restProps}>
        <Select
          placeholder="设置时间"
          allowClear={false}
          style={{ width: 200 }}
          value={timeSelected}
          options={timeInfo}
          onChange={selectChange}

        />
      </td>;
    }
    if (arr.includes(record.platformSetKey)) {
      return <td {...restProps}>
        <Select
          placeholder="选择地址"
          allowClear={false}
          style={{ width: 200 }}
          value={dArr}
          options={addressArrs}
          onChange={selectUrlChange}
        // onPopupScroll={(e) => {
        //   const { target } = e;
        //   // 判断是否滑动到底部
        //   if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
        //     //在这里调用接口
        //     ++pageNo;
        //     getMenu()
        //   }
        // }}
        />
      </td>;
    }
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
        rules={
          setRules(record)
        }
      >
        <Input ref={inputRef} onPressEnter={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

class PlatformSet extends Component {
  formRef = React.createRef()
  inputRef = React.createRef()
  state = {
    loading: false,
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    columns: [
      {
        title: '配置项',
        dataIndex: "platformSetKey",
        key: "platformSetKey",
        align: 'center',
        width: '50%',
      },
      {
        title: '值',
        dataIndex: "platformSetShowValue",
        key: "platformSetShowValue",
        align: 'center',
        editable: true,
        render: (text, record) => {
          return <div>
            {record.platformSetShowValue + record.platformSetUnit}
          </div>
        },
        width: '50%'
      },
    ],
    editIndex: null,
    editValue: ''
  }

  async componentDidMount() {
    await this.getData()
  }

  getData = async () => {
    const response = await apiGetPlatformSetList()
    if (response.code === 0) {
      const arr = response.data.map(v => {
        if (v.platformSetShow === 'Y')
          return v
      })
      this.setState({
        dataSource: arr
      })
    }

  }

  handleSave = async (row) => {
    let res = await apiGetPlatformSetEdit({ platformSetId: row.platformSetId, platformSetShowValue: row.platformSetShowValue })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '修改成功'
      })
      this.getData()
    }
  }
  render() {
    const { loading, dataSource } = this.state
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.state.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    return <div className={"p-layout-box configuration"}>
      <div className={'platform-set-list'}>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          dataSource={dataSource}
          columns={columns}
          loading={loading}
          pagination={false}
          scroll={{ y: '75vh' }}
          {...this.props}
        />
      </div>
    </div>
  }
}

export default PlatformSet